package cn._51doit.flink.day08;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * 在ProcessFunction中使用定时器
 *
 * 1.每个key都可以注册自己独立的定时器，定时器触发会调用onTimer，并且将对应的Key传入到OnTimerContext
 * 2.每个key多可以注册多个定时器，按照注册时间的先后顺序依次触发（如果注册了多个相同时间的定时器，只会触发一个）
 *
 *
 */

public class ProcessFunctionDemo3 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //开启checkpoint
        env.enableCheckpointing(5000);
        //设置重启策略
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(5, 5000));

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {
                if (line.startsWith("error")) {
                    throw new RuntimeException("有错误数据出现，抛出异常！");
                }
                String[] words = line.split(" ");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordAndOne.keyBy(t -> t.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> res = keyedStream.process(new WordCountKeyedProcessFunction2());

        res.print();

        env.execute();


    }


    /**
     * 在KeyedProcessFunction使用定时器
     */
    public static class WordCountKeyedProcessFunction2 extends KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>> {

        @Override
        public void processElement(Tuple2<String, Integer> input, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {


            long currentTimeMillis = System.currentTimeMillis();
            long triggerTime = currentTimeMillis + 15000;
            //定义了一个定时器（闹钟，在15秒后响）
            System.out.println(ctx.getCurrentKey() + " 注册了定时器，触发时间为： " + triggerTime);
            ctx.timerService().registerProcessingTimeTimer(triggerTime);

        }

        /**
         * 定时器触发后，会调用onTimer方法
         * @param timestamp
         * @param ctx
         * @param out
         * @throws Exception
         */
        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
            System.out.println(ctx.getCurrentKey() + " 在 " + timestamp + "触发的定时器");
        }
    }

}
